package com.authsphere.plugin.api;

import com.authsphere.common.result.ResponseResultUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;

/**
 * @program: AuthSphere
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/25 11:08
 **/
public class WebExchange {

    private HttpServletRequest request;
    private HttpServletResponse response;
    private Authentication authentication;
    private Object requestBody;
    private boolean abort;

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    public HttpServletResponse getResponse() {
        return response;
    }

    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }

    public Authentication getAuthentication() {
        return authentication;
    }

    public void setAuthentication(Authentication authentication) {
        this.authentication = authentication;
    }

    public Object getRequestBody() {
        return requestBody;
    }

    public void setRequestBody(Object requestBody) {
        this.requestBody = requestBody;
    }

    public boolean isAbort() {
        return abort;
    }

    public void setAbort(boolean abort) {
        this.abort = abort;
    }

    public static final class Builder {
        private HttpServletRequest request;
        private HttpServletResponse response;
        private Authentication authentication;
        private Object requestBody;

        private Builder() {
        }

        public static Builder builder() {
            return new Builder();
        }

        public Builder request(HttpServletRequest request) {
            this.request = request;
            return this;
        }

        public Builder response(HttpServletResponse response) {
            this.response = response;
            return this;
        }

        public Builder authentication(Authentication authentication) {
            this.authentication = authentication;
            return this;
        }

        public Builder requestBody(Object requestBody) {
            this.requestBody = requestBody;
            return this;
        }

        public WebExchange build() {
            WebExchange webExchange = new WebExchange();
            webExchange.setRequest(request);
            webExchange.setResponse(response);
            webExchange.setAuthentication(authentication);
            webExchange.setRequestBody(requestBody);
            return webExchange;
        }
    }

    public void result(Object result) {
        if (response.isCommitted()) {
            return;
        }
        ResponseResultUtils.result(response, result);
        setAbort(true);
    }
}
